package com.unitd.frame.springweb.interceptor;

import com.unitd.frame.springweb.annotation.CorsEnabled;
import org.springframework.http.HttpHeaders;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @desc SpringMVC的跨域访问拦截器,用于对跨域访问的方法进行拦截处理
 * @filename CorsEnableInterceptor.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/3/29
 */
public class CorsEnableInterceptor implements HandlerInterceptor {

	private final String allowOrigin = "*";
	private final String allowMethods = "GET,POST,OPTIONS";
	private final String allowHeaders = "Content-Type, Content-Length, X-Requested-With";

	/**
	 * @desc
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		if (handler instanceof HandlerMethod) {
			HandlerMethod method = (HandlerMethod) handler;
			CorsEnabled config = method.getMethod().getAnnotation(CorsEnabled.class);
			if (config != null) {
				response.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, allowOrigin);
				response.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, allowMethods);
				response.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, allowHeaders);
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
						   ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
}